package com.yf.boot.ability.oss.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.yf.boot.base.api.api.ApiRest;
import com.yf.boot.base.api.api.controller.BaseController;
import com.yf.boot.base.api.exception.ServiceException;
import com.yf.modules.sys.config.dto.CfgUploadOssDTO;
import com.yf.modules.sys.config.service.CfgUploadOssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 获取OSS文件上传令牌
 *
 * @author bool
 */
@Log4j2
@Api(tags = {"OSS文件上传"})
@RestController
public class OssController extends BaseController {

    @Autowired
    private CfgUploadOssService cfgUploadOssService;

    /**
     * 获得上传Token
     *
     * @return
     */
    @PostMapping("/api/ability/oss/token")
    @ApiOperation(value = "获得OSS上传token")
    public ApiRest<Map> token() {

        // 获得上传配置
        CfgUploadOssDTO conf = cfgUploadOssService.find();

        // 请填写您的AccessKeyId。
        String accessId = conf.getAccessKeyId();
        // 请填写您的AccessKeySecret。
        String accessKey = conf.getAccessKeySecret();
        // 请填写您的 endpoint。
        String endpoint = conf.getEndpoint() + ".aliyuncs.com";
        // 请填写您的 bucketname 。
        String bucket = conf.getBucket();
        // host的格式为 bucketname.endpoint
        String host = "https://" + bucket + "." + endpoint;
        // 用户上传文件时指定的前缀。
        String dir = "";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        try {

            // 授权30分钟有效
            long expireTime = 1800;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));

            // 带入访问URL
            respMap.put("url", conf.getUrl());

            return super.success(respMap);
        } catch (Exception e) {
            log.error(e);
            throw new ServiceException("OSS上传令牌获取失败！");
        } finally {
            ossClient.shutdown();
        }

    }
}
